<?php
class fwDictionary
{
	/** language of target translation
	 *  @var string */
	public $language;

	/**
	 * Dictionary used in statyic methode
	 *
	 * @var fwDictionary
	 */
	private static $globalDictionary = null;
	
	/**
	 * Create a new instance of fwDictionary
	 *
	 * @param string $p_language default language
	 */
	public function __construct($p_language='')
	{
		if($p_language!='')
		{
			$this->language = strtolower($p_language);
		}	
		elseif(isset($_SESSION['current_user']))
		{
			$this->language = strtolower($_SESSION['current_user']->language);
		}
		else
		{
			$this->language = 'fr';
		}
	}

	/**
	 * Start the buffer
	 *
	 */
	public static function start()
	{
		header('Content-Type: text/html; charset=UTF-8');
		self::$globalDictionary = new fwDictionary();
		ob_start('fwDictionary_stop');
	}

	/**
	 * Stop the buffer and translate
	 *
	 */
	public static function stop($contents)
	{
		if(self::$globalDictionary == null)
		{
			return;
		}
		if(isset($_SESSION['connected_user']) && $_SESSION['connected_user']->language!='')
		{
			self::$globalDictionary->language = strtolower($_SESSION['connected_user']->language);
		}
		$contents = ob_get_contents();
		return self::$globalDictionary->translate($contents);
	}

	private function _getDictionariesFolder()
	{
		global $project_path;
		if(!is_dir($project_path.'/lang/'.$this->language))
		{
			fwTools::mkdirTree($project_path, '/lang/'.$this->language);
		}
		
		return $project_path.'/lang/'.$this->language;
	}
	
	public static function getDictionariesFolder()
	{
		return self::$globalDictionary->_getDictionariesFolder();
	}
	
	/**
	 * Get the list of dictionnaries installed
	 * 
	 * @return array
	 */
	public static function getDictionariesFolders()
	{
		global $project_path;
		$dictionaries = array();
		$h = opendir($project_path.'/lang/');
		while($f = readdir($h))
		{
			if($f=='.' || $f=='..' || !is_dir($project_path.'/lang/'.$f))
			{
				continue;
			}
			if(!file_exists($project_path.'/lang/'.$f.'/index.php'))
			{
				continue;
			}
			include $project_path.'/lang/'.$f.'/index.php';
			$dictionaries[$f] = $lang_info;
		}
		return $dictionaries;
	}
	
	public static function translateSentence($sentence)
	{
		if(self::$globalDictionary == null)
		{
			self::$globalDictionary = new fwDictionary();
		}

		return self::$globalDictionary->translate($sentence);
	}
	
	/**
	 * Translate a contents
	 *
	 * @param string $contents text to translate
	 */
	public function translate($contents)
	{
		global $project_path;
		//Search the words to translate
		$out='';
		preg_match_all('`\«[!]?([A-Z\\_]+)\»`', $contents, $out, PREG_PATTERN_ORDER);

		$words = array_unique($out[1]);
		$words_group = array();
		
		$replace_search = array();
		$replace_replace = array();
		
		foreach ($words as $word)
		{
			$pos = strpos($word, '_');
			if($pos===false)
			{
				$replace_search[] = '«'.$word.'»';
				$replace_replace[] = '«'.$word.'»';
				$replace_search[] = '«!'.$word.'»';
				$replace_replace[] = addslashes('«'.$word.'»');
				continue;
			}
			$words_group[substr($word, 0, $pos)][] = substr($word, $pos+1);
		}

		//nothing to translate ?
		if(count($words_group)==0)
		{
			return $contents;
		}

		$dictionary_folder = self::_getDictionariesFolder();
		if(!is_dir($dictionary_folder))
		{
			mkdir($dictionary_folder);
		}
		
		//load the dictionaries
		foreach ($words_group as $group => $words)
		{
			$untransalted_words = array();
			$file_path = $dictionary_folder.'/'.strtolower($group).'.lng.php';
			if(!file_exists($file_path))
			{
				file_put_contents($file_path, 'array();');
				$dic = array();
			}
			else 
			{
				eval('$dic='.file_get_contents($file_path));
			}
			if(is_writable($file_path))
			{
				foreach ($words as $word)
				{
					if(isset($dic[$word]))
					{
						$replace_search[] = '«'.$group.'_'.$word.'»';
						$replace_replace[] = $dic[$word];
						$replace_search[] = '«!'.$group.'_'.$word.'»';
						$replace_replace[] = addslashes($dic[$word]);
					}
					else 
					{
						$replace_search[] = '«'.$group.'_'.$word.'»';
						$replace_replace[] = '«'.$word.'»';
						$replace_search[] = '«!'.$group.'_'.$word.'»';
						$replace_replace[] = addslashes('«'.$word.'»');
						$untransalted_words[] = $word;
					}
				}
			}
			else 
			{
				foreach ($words as $word)
				{
					if(isset($dic[$word]))
					{
						$replace_search[] = '«'.$group.'_'.$word.'»';
						$replace_replace[] = $dic[$word];
						$replace_search[] = '«!'.$group.'_'.$word.'»';
						$replace_replace[] = addslashes($dic[$word]);
					}
					else 
					{
						$replace_search[] = '«'.$group.'_'.$word.'»';
						$replace_replace[] = '«'.$word.'»';
						$replace_search[] = '«!'.$group.'_'.$word.'»';
						$replace_replace[] = addslashes('«'.$word.'»');
					}
				}
			}
			if(count($untransalted_words)>0)
			{
				foreach ($untransalted_words as $word)
				{
					$dic[$word] = '«'.$word.'»';
				}
				file_put_contents($file_path, fwTools::var_export_string($dic).';');
			}
		}
		
		return str_replace($replace_search, $replace_replace, $contents);
	}
}
function fwDictionary_stop($content)
{
	return fwDictionary::stop($content);
}
fwDictionary::start();